import { createVNode, render, h, ref } from "vue";
import CoolDialog from "@/components/CoolDialog.vue";

// 确认弹窗组件
const CoolConfirm = {
  name: "CoolConfirm",
  props: {
    title: {
      type: String,
      default: "确认提示",
    },
    message: {
      type: String,
      default: "确定要执行此操作吗？",
    },
    cancelButtonText: {
      type: String,
      default: "取消",
    },
    confirmButtonText: {
      type: String,
      default: "确认",
    },
  },
  emits: ["confirm", "cancel"],
  setup (props, { emit }) {
    const visible = ref(true);

    const handleCancel = () => {
      visible.value = false;
      emit("cancel");
    };

    const handleConfirm = () => {
      visible.value = false;
      emit("confirm");
    };

    return {
      visible,
      handleCancel,
      handleConfirm,
    };
  },
  render () {
    return h(
      CoolDialog,
      {
        modelValue: this.visible,
        "onUpdate:modelValue": (val) => (this.visible = val),
        title: this.title,
        onCancel: this.handleCancel,
        onConfirm: this.handleConfirm,
      },
      {
        default: () =>
          h("div", { class: "cool-confirm-content" }, this.message),
        footer: () =>
          h("div", { class: "cool-dialog-footer" }, [
            h(
              "button",
              {
                class: "cool-button cool-button-cancel",
                onClick: this.handleCancel,
              },
              this.cancelButtonText,
            ),
            h(
              "button",
              {
                class: "cool-button cool-button-confirm",
                onClick: this.handleConfirm,
              },
              this.confirmButtonText,
            ),
          ]),
      },
    );
  },
};

// 创建弹窗实例
const createConfirmInstance = (options) => {
  // 默认配置
  const defaultOptions = {
    title: "确认提示",
    message: "确定要执行此操作吗？",
    cancelButtonText: "取消",
    confirmButtonText: "确认",
  };

  // 合并配置
  const finalOptions = {
    ...defaultOptions,
    ...(typeof options === "string" ? { message: options } : options),
  };

  return new Promise((resolve, reject) => {
    // 创建容器
    const container = document.createElement("div");

    // 创建组件
    const vnode = createVNode(CoolConfirm, {
      ...finalOptions,
      onConfirm: () => {
        // 确认回调
        render(null, container);
        container.parentNode?.removeChild(container);
        resolve(true);
      },
      onCancel: () => {
        // 取消回调
        render(null, container);
        container.parentNode?.removeChild(container);
        reject(new Error("用户取消"));
      },
    });

    // 渲染组件
    render(vnode, container);
    document.body.appendChild(container);
  });
};

// 导出API
const coolConfirm = {
  // 基础调用
  confirm (options) {
    return createConfirmInstance(options);
  },

  // 指定标题调用
  withTitle (title, message) {
    return createConfirmInstance({ title, message });
  },
};

export default coolConfirm;
